package edu.washington.ling.syntric.pipeline;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class MultithreadedProcedure implements Runnable {
	private int maxThreads;
	private List<Thread> threads;
	public MultithreadedProcedure(int maxThreads) {
		this.maxThreads = maxThreads;
		threads = new ArrayList<Thread>();
	}
	public void addThread(Thread thread) {
		threads.add(thread);
	}
	public void addRunnable(Runnable runnable) {
		threads.add(new Thread(runnable));
	}
	@Override
	public void run() {
		List<Thread> activeThreads = new LinkedList<Thread>();
		for (int i = 0; i < threads.size(); i++) {
			threads.get(i).start();
			activeThreads.add(threads.get(i));
			if(activeThreads.size() == maxThreads || i == threads.size() - 1) {
				for (Thread activeThread: activeThreads) {
					try {
						activeThread.join();
					} catch(InterruptedException e) {
						e.printStackTrace();
					}
				}
				activeThreads = new LinkedList<Thread>();
			}
		}	
	}
}
